import { Button, Card, Popconfirm, Table, Image, message } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { useEffect, useState } from 'react';

import bannerService from '@/api/services/setting/bannerService';
import { Iconify } from '@/components/icon';
import TipIconButton from '@/components/icon/tooltip-icon-button';
import { SearchForm } from '@/pages/management/system/role/search-form';
import { datetime } from '@/utils/format-date';
import { hasPermission } from '@/utils/permission';

import { BannerModal } from './banner-modal';
import { BannerType } from './type';

import { ModalProps, UserInfo } from '#/entity';

const { VITE_APP_DOMAIN: DOMAIN } = import.meta.env;

function Banner() {
  const [searchForm, setSearchForm] = useState<SearchForm>({
    page: 1,
    take: 100000,
  });
  const [tableData, setTableData] = useState<BannerType[]>();
  // 获取数据
  useEffect(() => {
    bannerService.getBannersList(searchForm).then((res) => {
      setTableData(res);
    });
  }, [searchForm]);
  const [modalProps, setModalProps] = useState<ModalProps<BannerType>>({
    formValue: {},
    title: '',
    show: false,
    onOk: () => {
      setModalProps((prev) => ({
        ...prev,
        show: false,
      }));
      setSearchForm((prev) => ({ ...prev, page: 1 }));
    },
    onCancel: () => {
      setModalProps((prev) => ({ ...prev, show: false }));
    },
  });

  const columns: ColumnsType<BannerType> = [
    {
      title: '横幅图片',
      dataIndex: 'file',
      render: (file: number) => <Image src={`${DOMAIN}/api/file/oss/${file}`} width={60} alt="" />,
    },
    {
      title: '横幅标题',
      dataIndex: 'name',
    },

    {
      title: '横幅排序',
      dataIndex: 'sort',
    },
    {
      title: '跳转链接',
      dataIndex: 'redirectUrl',
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: (createBy: UserInfo) => {
        return createBy.name;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      render: (createAt: Number[]) => {
        return datetime(createAt);
      },
    },
    {
      title: <div style={{ marginRight: 20 }}>操作</div>,
      align: 'right',
      dataIndex: 'action',
      render: (_: any, record: any) => (
        <div className="flex w-full justify-end text-gray">
          {hasPermission('LOGISTICS:BANNER:UPDATE') && (
            <TipIconButton onClick={() => onEdit(record)} tipText="修改该张横幅信息">
              <Iconify icon="solar:pen-bold-duotone" size={18} />
            </TipIconButton>
          )}
          {hasPermission('LOGISTICS:BANNER:DELETE') && (
            <Popconfirm
              title={operationDeleteTitle()}
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                onDelete(record);
              }}
              placement="left"
            >
              <TipIconButton tipText="删除">
                <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
              </TipIconButton>
            </Popconfirm>
          )}
        </div>
      ),
    },
  ];
  const operationDeleteTitle = () => {
    return '确定删除吗？';
  };
  const onCreate = () => {
    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '新增横幅',
      formValue: {},
    }));
  };

  const onEdit = (record: any) => {
    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '修改横幅',
      formValue: {
        ...record,
      },
      onOk: () => {
        setModalProps((prev) => ({
          ...prev,
          show: false,
          formValue: {},
        }));
        setSearchForm({ page: 1, take: 10 });
      },
    }));
  };
  const onDelete = (record: BannerType) => {
    bannerService.deleteBanner(record.id!).then((res) => {
      if (res > 0) {
        message.success('删除成功');
      }
      setSearchForm({ page: searchForm.page, take: searchForm.take });
    });
  };
  return (
    <Card
      title="横幅"
      extra={
        <div className="flex items-center gap-2">
          {hasPermission('LOGISTICS:BANNER:CREATE') && (
            <Button
              type="primary"
              // disabled={!hasPermission('SECURITY:USER:CREATE')}
              onClick={onCreate}
            >
              新增
            </Button>
          )}
        </div>
      }
    >
      <Table<BannerType>
        size="small"
        rowKey="id"
        columns={columns}
        dataSource={tableData}
        pagination={false}
      />
      <BannerModal {...modalProps} />
    </Card>
  );
}

export default Banner;
